package com.zmn.oms.task.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.consts.GlobalConsts;
import com.zmn.manager.mq.annotation.AliyunMQHandler;
import com.zmn.manager.mq.annotation.AliyunMQListener;
import com.zmn.oms.business.interfaces.warningnews.OmsOrderWarningNewsBService;
import com.zmn.oms.business.interfaces.work.tag.OrderTagBService;
import com.zmn.oms.common.constant.MessageRuleIdConsts;
import com.zmn.oms.common.constant.OrderTagConsts;
import com.zmn.oms.manager.utils.OmsMqTagConsts;
import com.zmn.oms.model.bo.work.redistribute.OrderWorkRedistributeApplyBO;
import com.zmn.oms.model.bo.work.redistribute.OrderWorkRedistributeModifyBO;
import com.zmn.oms.model.dto.tag.OrderTagAddDTO;
import com.zmn.oms.model.entity.redistribute.OrderWorkRedistributeApply;
import com.zmn.oms.services.interfaces.redistribute.OrderWorkRedistributeApplyService;
import com.zmn.oms.zmn.business.interfaces.message.SendOrderNodeMsgService;
import com.zmn.oms.zmn.business.interfaces.redistribute.OrderWorkRedistributeApplyBService;
import com.zmn.oms.zmn.business.interfaces.redistribute.RedistributeApplyBService;
import com.zmn.performance.common.constant.OrderTimeoutConsts;
import com.zmn.performance.common.enums.OrderWarningTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.Optional;

/**
 * 类描述：预警消息
 *
 * @author liuying
 * @date 2021/12/27 14:18
 */
@Slf4j
@AliyunMQListener(topic = "${spring.mq.topic.oms}")
@Component
public class PerformanceListener {

    @Autowired
    private OrderTagBService orderTagBService;
    @Resource
    private SendOrderNodeMsgService sendOrderNodeMsgService;
    @Autowired
    private OrderWorkRedistributeApplyBService orderWorkRedistributeApplyBService;
    @Resource
    private OrderWorkRedistributeApplyService orderWorkRedistributeApplyService;
    @Resource
    private RedistributeApplyBService redistributeApplyService;
    @Resource
    private OmsOrderWarningNewsBService omsOrderWarningNewsBService;

    /**
     * 超时预警通知
     *
     * @param message
     */
    @AliyunMQHandler(tags = OmsMqTagConsts.PERFORMANCE_TAG_TIME_OUT_NOTICE_TAG)
    public void performanceTimeOutNotice(String message) {
        log.info("#oms#performance# 收到超时预警消息通知[{}]", message);
        if (StringUtil.isBlank(message)) {
            return;
        }
        // orderId---订单号
        // timeoutType----超时类型（com.zmn.performance.common.constant.OrderTimeoutConsts#TIME_OUT_TYPE_CONTACT）
        try {
            JSONObject jsonObject = JSON.parseObject(message);
            Long orderId = jsonObject.getLong("orderId");
            Long workId = Optional.ofNullable(jsonObject.getLong("workId")).orElse(null);
            Long redistributeId = jsonObject.getLong("redistributeId");
            Integer timeoutType = jsonObject.getInteger("timeoutType");

            // 上门超时，发送迟到安抚消息
            if (Objects.equals(OrderTimeoutConsts.TIME_OUT_TYPE_VISIT, timeoutType)) {
                sendOrderNodeMsgService.submitOrderMsg(orderId, orderId, MessageRuleIdConsts.MESSAGE_GLOBAL_VISIT_TIME_OUT_NODE_MARK,
                        MessageRuleIdConsts.MESSAGE_GLOBAL_VISIT_TIME_OUT_NODE_MARK, null, null);
            }

            // 这个地方只要联系超时
            if (Objects.equals(timeoutType, OrderTimeoutConsts.TIME_OUT_TYPE_CONTACT)) {
                OrderTagAddDTO orderTagAddDTO = new OrderTagAddDTO();
                orderTagAddDTO.setOrderId(orderId);
                orderTagAddDTO.setWorkId(orderId);
                orderTagAddDTO.setTagIdList(Lists.newArrayList(OrderTagConsts.TAG_ID_WARNING_CONTACT_TIMEOUT));
                orderTagBService.addOrderTag(orderTagAddDTO);
            }

            // 处理超时事件
            switch (timeoutType) {
                case OrderTimeoutConsts.TIME_OUT_TYPE_TAKE_REDISTRIBUTE:
                    // 首次领单超时
                    OrderWorkRedistributeApplyBO applyBO = JSON.toJavaObject(jsonObject, OrderWorkRedistributeApplyBO.class);
                    applyBO.setOperatorId(Long.valueOf(GlobalConsts.OPERATE_USER_TYPE_SYSTEM));
                    applyBO.setOperator(GlobalConsts.getOperatorTypeName(GlobalConsts.OPERATE_USER_TYPE_SYSTEM));
                    applyBO.setOperatorType(GlobalConsts.OPERATE_USER_TYPE_SYSTEM);
                    applyBO.setOperateTime(DateUtil.getNow());
                    applyBO.setRedistributeId(null);
                    redistributeApplyService.autoRedistributeApply(applyBO);
                    break;

                case OrderTimeoutConsts.TIME_OUT_TYPE_REDISTRIBUTE:
                    //  转单求助超时
                    OrderWorkRedistributeModifyBO modifyBO = JSON.toJavaObject(jsonObject, OrderWorkRedistributeModifyBO.class);
                    modifyBO.setOperatorId(Long.valueOf(GlobalConsts.OPERATE_USER_TYPE_SYSTEM));
                    modifyBO.setOperator(GlobalConsts.getOperatorTypeName(GlobalConsts.OPERATE_USER_TYPE_SYSTEM));
                    modifyBO.setOperatorType(GlobalConsts.OPERATE_USER_TYPE_SYSTEM);
                    modifyBO.setOperateTime(DateUtil.getNow());
                    redistributeApplyService.helpTakeTimeOut(modifyBO);
                    break;

                case OrderTimeoutConsts.TIME_OUT_TYPE_REDISTRIBUTE_CHECK:
                    // 改派审核超时
                    OrderWorkRedistributeApply redistributeApply = new OrderWorkRedistributeApply();
                    redistributeApply.setRedistributeId(redistributeId);
                    redistributeApply.setOrderId(orderId);
                    redistributeApply.setAuditTimeoutStatus(GlobalConsts.YES);
                    orderWorkRedistributeApplyService.updateByPrimaryKeySelective(redistributeApply);
                    break;
                default:
                    log.error("工单号：[{}]，无效的预警超时类型。", orderId);
                    break;
            }
            // 保存日志 发送APP push 消息
            omsOrderWarningNewsBService.timeOutNoticeSaveOrderLogAndSendAppPush(workId, orderId, timeoutType);
        } catch (Exception ex) {
            log.error("预警消息处理失败：{}", ex);
        }
    }


    /**
     * 预警提醒通知 入参：
     * <p>
     * orderId 订单号 <br>
     * warningType 提醒类型 <br>
     * redistributeId 改派申请ID
     *
     * @param message
     */
    @AliyunMQHandler(tags = OmsMqTagConsts.PERFORMANCE_TAG_WARNING_NOTICE_TAG)
    public void performanceWarningNotice(String message) {
        log.info("#oms#performance# 收到【预警提醒】消息通知[{}]", message);
        if (StringUtil.isBlank(message)) {
            log.error("#oms#performance# MQ消息未接收到任何数据。");
            return;
        }

        try {
            JSONObject jsonObject = JSON.parseObject(message);
            Long orderId = jsonObject.getLong("orderId");
            Long redistributeId = jsonObject.getLong("redistributeId");
            Integer warningType = jsonObject.getInteger("warningType");
            Long workId = Optional.ofNullable(jsonObject.getLong("workId")).orElse(null);
            // 保存日志 发送APP push 消息
            omsOrderWarningNewsBService.warningNoticeSaveOrderLogAndSendAppPush(workId, orderId, warningType);
            // 审核预警 - 含义：5分钟内未进行审核操作
            if (Objects.equals(warningType, OrderWarningTypeEnum.REDISTRIBUTE_CHECK.getCode())) {
                OrderWorkRedistributeApply redistributeApply = new OrderWorkRedistributeApply();
                redistributeApply.setRedistributeId(redistributeId);
                redistributeApply.setOrderId(orderId);
                redistributeApply.setAuditWarningStatus(GlobalConsts.YES);
                orderWorkRedistributeApplyService.updateByPrimaryKeySelective(redistributeApply);
            }

        } catch (Exception ex) {
            log.error("预警消息处理失败", ex);
        }
    }
}
